<template>
  <el-dialog :model-value="visible" :title="formModel.id ? '修改' : '添加'" width="600px" center align-center destroy-on-close @close="onClose">
    <el-form ref="formRef" :model="formModel" :rules="rules" label-width="80px" @submit.prevent>
      <el-form-item class="form-group" label="用户头像" prop="userHead">
        <selector-image v-model="formModel.userHead" :width="'120px'" :height="'120px'" :sug-img="'尺寸：120x120px，格式：JPG、PNG，大小：<2M'" />
      </el-form-item>
      <el-form-item v-if="!formModel.id" class="form-group" label="手机号码" prop="mobile">
        <el-input v-model="formModel.mobile" maxlength="11" show-word-limit></el-input>
      </el-form-item>
      <el-form-item v-if="!formModel.id" class="form-group" label="登录密码" prop="mobilePwd">
        <el-input v-model="formModel.mobilePwd" maxlength="50" type="password" show-word-limit show-password></el-input>
      </el-form-item>
      <el-form-item class="form-group" label="用户昵称" prop="nickname">
        <el-input v-model="formModel.nickname" maxlength="20" show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="用户性别" prop="userSex">
        <enum-radio v-model="formModel.userSex" :enum-name="'UserSex'"></enum-radio>
      </el-form-item>
      <el-form-item class="form-group" label="出生日期" prop="userAge">
        <el-date-picker v-model="formModel.userAge" value-format="YYYY-MM-DD" format="YYYY-MM-DD" type="date" placeholder="请选择出生日期" />
      </el-form-item>
      <el-form-item class="form-group" label="备注" prop="remark">
        <el-input v-model="formModel.remark" maxlength="200" type="textarea" show-word-limit></el-input>
      </el-form-item>
      <el-form-item class="form-group" label="标签" prop="remark">
        <el-tag v-for="tag in selectedTags" :key="tag.id" size="large" closable :disable-transitions="false" class="tagItem" @close="handleTagRemove(tag)">
          {{ tag.tagName }}
        </el-tag>
        <el-button :icon="'Plus'" @click="openTagSelect()">选择标签</el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="onClose()">取消</el-button>
      <el-button type="primary" @click="onSubmit()">确定</el-button>
    </template>

    <selector-tag v-if="selectorTagVisible" :tags="selectedTags" @close="handleTagSelect" />
  </el-dialog>
</template>

<script setup>
  import { ElMessage } from 'element-plus'
  import { ref } from 'vue'
  import { commonApi } from '@/api/common.js'
  import EnumRadio from '@/components/Enum/Radio/index.vue'
  import SelectorTag from '@/components/Selector/Tag/index.vue'
  import SelectorImage from '@/components/Selector/Image/index.vue'

  // 选择标签
  const selectorTagVisible = ref(false)
  const selectedTags = ref([])
  const openTagSelect = () => {
    selectorTagVisible.value = true
  }
  const handleTagSelect = (tags) => {
    if (tags && tags.length > 0) {
      selectedTags.value = tags
    }
    selectorTagVisible.value = false
  }
  const handleTagRemove = (tag) => {
    selectedTags.value = selectedTags.value.filter((t) => t.id !== tag.id)
  }

  // 打开和关闭
  const onOpen = (item) => {
    formModel.value = {
      id: undefined,
      sort: 1,
      userSex: 1,
      tagIds: undefined
    }
    if (item) {
      commonApi.usersView({ id: item.id }).then((res) => {
        Object.assign(formModel.value, res)
        selectedTags.value = res.tags
      })
    }
    visible.value = true
  }
  defineExpose({ onOpen })
  const onClose = () => {
    visible.value = false
  }

  // 表单
  const formModel = ref({
    id: undefined,
    sort: 1,
    tagIds: undefined
  })
  const onSubmit = async () => {
    // 校验
    const valid = await formRef.value.validate()
    if (!valid) return
    if (loading.value === true) {
      ElMessage.warning('正在处理...')
      return
    }

    formModel.value.tagIds = selectedTags.value.map((item) => item.id)

    loading.value = true
    try {
      if (formModel.value.id) {
        await commonApi.usersEdit(formModel.value)
        ElMessage.success('修改成功')
      } else {
        await commonApi.usersSave(formModel.value)
        ElMessage.success('添加成功')
      }
      emit('refresh')
      onClose()
    } finally {
      loading.value = false
    }
  }

  // 规则
  const formRef = ref()
  const rules = {
    userHead: [{ required: true, message: '不能为空', trigger: 'blur' }],
    mobile: [
      { required: true, message: '不能为空', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式错误', trigger: 'blur' }
    ],
    mobilePwd: [{ required: true, message: '不能为空', trigger: 'blur' }],
    nickname: [{ required: true, message: '不能为空', trigger: 'blur' }]
  }

  const emit = defineEmits(['refresh'])
  const visible = ref(false)
  const loading = ref(false)
</script>
<style lang="scss" scoped>
  .tagItem {
    margin: 5px;
  }
</style>
